//
//  DB_NetFollowReading.m
//  KidReading
//
//  Created by YangShuai on 16/9/30.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "DB_NetFollowReading.h"
#import "ConstDefine.h"

@interface DB_NetFollowReading ()
@property(nonatomic,strong)JRAFURLSessionManager* sessionManager;
@property(nonatomic,strong)NSDictionary* runingCellInfo;
@end

static DB_NetFollowReading* singleDB_netFR = nil;

@implementation DB_NetFollowReading

+ (DB_NetFollowReading*)shareSingle{
    if (singleDB_netFR == nil) {
        @synchronized (self) {
            singleDB_netFR = [[DB_NetFollowReading alloc] init];
        }
    }
    return singleDB_netFR;
}
//获取cache目录跟地址
-(NSString*)getCacheDirFilePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesDir = [paths objectAtIndex:0];
    return cachesDir;
}

//通过相对路径获取FullPath
-(NSString*)getFullPathWithRelativePath:(NSString*)relativePath{
    NSString *cachesDir = [self getCacheDirFilePath];
    NSString* relativeDirPath = [relativePath stringByDeletingLastPathComponent];
    NSString* recordFileDir = [cachesDir stringByAppendingPathComponent:relativeDirPath];
    BOOL isDirectory = NO;
    BOOL isFileExists = NO;
    isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:recordFileDir isDirectory:&isDirectory];
    if (!isDirectory && isFileExists) {
        [[NSFileManager defaultManager] removeItemAtPath:recordFileDir error:nil];
    }
    if (!isDirectory || !isFileExists) {
        [[NSFileManager defaultManager] createDirectoryAtPath:recordFileDir withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
    return [cachesDir stringByAppendingPathComponent:relativePath];
}

//


//判断是否包含该句录音
- (void)isContainWordRecordWithBookId:(NSInteger)bookId PageIndex:(NSInteger)pageIndex SenIndex:(NSInteger)senIndex IsExist:(void(^)(NSString* localFullPath, NSString* relativePath,BOOL isLocalExist,BOOL isSeverExist))isExist{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    [[DBHelper shareInstance] followReading_getDictList:^(NSArray *list) {
        if (list.count == 1) {
            NSDictionary* sentenceDict = [list firstObject];
            if (isExist) {
                NSString* recordRelativePath = sentenceDict[@"radioSrc"];
                NSString* recordFullPath = [self getFullPathWithRelativePath:recordRelativePath];
                if ([[NSFileManager defaultManager] fileExistsAtPath:recordFullPath]) {
                    isExist(recordFullPath,recordRelativePath,YES,YES);
                }else{
                    isExist(recordFullPath,recordRelativePath,NO,YES);
                }
            }
        }else{
            if (isExist) isExist(nil,nil,NO,NO);
        }
    } fromTableClass:NSStringFromClass([OneWordASRResult class]) where:[NSString stringWithFormat:@"where userId = %@ and bookId = %@ and pageIndex = %@ and senIndex = %@",@(uinfo.uid),@(bookId),@(pageIndex),@(senIndex)]];
}
//
-(JRAFURLSessionManager *)sessionManager{
    if (_sessionManager == nil) {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        _sessionManager = [[JRAFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        _sessionManager.operationQueue.maxConcurrentOperationCount = 3;
    }
    return _sessionManager;
}
//下载某一句的录音
-(void)downloadRecordWithRelativePath:(NSString*)relativePath LocalFullPath:(NSString*)localFullPath completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler{
    //
    NSString* recordPath = [NSString stringWithFormat:@"%@%@",[DataProcessing shareSingle].audio_file_url, relativePath];
    NSURLSessionDownloadTask* downloadTask = [self.sessionManager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:recordPath]] progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString* dirFilePath = [localFullPath stringByDeletingLastPathComponent];
        NSURL* pagePathUrl = [NSURL fileURLWithPath:dirFilePath];
        NSURL* recordPathUrl = [pagePathUrl URLByAppendingPathComponent:[response suggestedFilename]];
        return recordPathUrl;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (response) {
            if (completionHandler) completionHandler(response,filePath,error);
        }
    }];
    [downloadTask resume];
}

//干掉当前页的录音
- (void)removeCurrentLocalRecordWithBookId:(NSInteger)bookId PageIndex:(NSInteger)pageIndex SenIndex:(NSInteger)senIndex{
    [self isContainWordRecordWithBookId:bookId PageIndex:pageIndex SenIndex:senIndex IsExist:^(NSString *localFullPath, NSString* relativePath, BOOL isLocalExist, BOOL isSeverExist) {
        [[NSFileManager defaultManager] removeItemAtPath:localFullPath error:nil];
    }];
}


//将录音文件上传至upYUn
-(void)uploadFollowReadingRecordFileWithSaveKey:(NSString*)saveKey EvalResultDict:(NSDictionary*)evalResultDict Success:(void (^)(NSURLResponse *response, id responseData))success Failure:(void (^)(NSError *error))failure Progress:(void (^)(CGFloat percent, int64_t requestDidSendBytes))progress{
    NSData* recordData = [NSData dataWithContentsOfFile:[self getFullPathWithRelativePath:saveKey]];
    
    UpYun *uy = [[UpYun alloc] init];
    
    uy.successBlocker = ^(NSURLResponse *response, id responseData)
    {
        //上传成功后与服务器通信
        [[NetGetPostsWithCache shareInstance] updateOrGetOnePageRadioEvalsWithBookId:0 PageIndex:0 EvalJsonStr:[self getSeverNeedResultJsonStrResultDict:evalResultDict] Success:^(NSDictionary *retDict) {
            //上传成功并且与服务器通信成功
            if (success) success(response,responseData);
        } Failure:^(NSError *error) {
            [[DB_NetFollowReading shareSingle] updateUploadFailedASRResultToDBWithDict:evalResultDict];
            if (failure) failure(error);
        }];
    };
    uy.failBlocker = ^(NSError *error)
    {
        //失败信息存储到数据库
        [[DB_NetFollowReading shareSingle] updateUploadFailedASRResultToDBWithDict:evalResultDict];
        if (failure) failure(error);
    };
    uy.progressBlocker = ^(CGFloat percent, int64_t requestDidSendBytes)
    {
        if (progress) progress(percent,requestDidSendBytes);
    };
    [uy uploadFile:recordData saveKey:saveKey];
}
//
//将评测结果转化为服务器需要的参数格式(jsonString)
-(NSString*)getSeverNeedResultJsonStrResultDict:(NSDictionary*)resultDict{
    NSString* jsondate = @"";
    NSData* Data = [NSJSONSerialization dataWithJSONObject:@[resultDict] options:NSJSONWritingPrettyPrinted error:nil];
    if (Data) {
        jsondate = [[NSString alloc] initWithBytes:Data.bytes length:Data.length encoding:NSUTF8StringEncoding];
    }
    return jsondate;
}

//成功存储数据库
-(void)updateASRResultToDBWithDict:(NSDictionary*)resultDict Complete:(void (^)(void))complete{
    [[DBHelper shareInstance] followReading_updateListToTableClass:NSStringFromClass([OneWordASRResult class]) dictArr:@[resultDict] complete:^{
        if (complete) {
            complete();
        }
    }];
}
//上传同步失败存储数据库
-(void)updateUploadFailedASRResultToDBWithDict:(NSDictionary*)resultDict{
    [[DBHelper shareInstance] followReading_updateListToTableClass:NSStringFromClass([OneWordASRResult_Failure class]) dictArr:@[resultDict] complete:nil];
}

//同步上传失败的文件
-(void)reUpdateRecordAndASRResultWithBookId:(NSInteger)bookId{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    [[DBHelper shareInstance] followReading_getDictList:^(NSArray *list) {
        for (NSDictionary* failedDict in list) {
            [self uploadFollowReadingRecordFileWithSaveKey:failedDict[@"radioSrc"] EvalResultDict:failedDict Success:^(NSURLResponse *response, id responseData) {
                NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithDictionary:failedDict];
                [dict removeObjectForKey:@"evalInfo"];
                [[DBHelper shareInstance] followReading_deletListToTableClass:NSStringFromClass([OneWordASRResult_Failure class]) dictArr:@[dict] complete:nil];
            } Failure:nil Progress:nil];
        }
        
    } fromTableClass:NSStringFromClass([OneWordASRResult_Failure class]) where:[NSString stringWithFormat:@"where userId = %@ and bookId = %@",@(uinfo.uid),@(bookId)]];
}

//更新当前正在运行的Cell以及为哪个button
-(void)updateRuningCellWithBookId:(NSInteger)bookId PageIndex:(NSInteger)pageIndex SentenceId:(NSInteger)sentenceId RuningBtn:(StatusButton*)runingBtn CurrentTime:(NSTimeInterval)currentTime{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    NSString* key = [NSString stringWithFormat:@"%@_%@_%@_%@",@(uinfo.uid),@(bookId),@(pageIndex),@(sentenceId)];
    self.runingCellInfo = @{key:@{@"runingBtn":runingBtn,@"time":@(currentTime)}};
}

//无CellRuing
-(void)cleanRuningCellInfo{
    self.runingCellInfo = nil;
}

//记录当前正在播放的Cell以及当前的按钮进度
-(void)checkCellIsRuningWithBookId:(NSInteger)bookId PageIndex:(NSInteger)pageIndex SentenceId:(NSInteger)sentenceId Complete:(void(^)(BOOL isRuning, StatusButton* runingButton, NSTimeInterval currentTime))complete{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    NSString* key = [NSString stringWithFormat:@"%@_%@_%@_%@",@(uinfo.uid),@(bookId),@(pageIndex),@(sentenceId)];
    BOOL isRuning = NO;
    StatusButton* runingBtn = nil;
    CGFloat currentTime = 0;
    if (_runingCellInfo[key]) {
        isRuning = YES;
        runingBtn = _runingCellInfo[key][@"runingBtn"];
        currentTime = [_runingCellInfo[key][@"time"] floatValue];
        if (complete) complete(isRuning,runingBtn,currentTime);
    }else{
        if (complete) complete(isRuning,runingBtn,currentTime);
    }
}


@end
